package com.star.oauth2.client.controller;

import com.star.oauth2.client.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 令牌控制器
 * 
 * 提供前端获取和刷新OAuth2令牌的接口
 * 
 * @author star
 */
@Slf4j
@RestController
@RequestMapping("/api/token")
public class TokenController {

    @Autowired
    private TokenService tokenService;
    
    /**
     * 使用授权码获取令牌
     * 
     * @param code 授权码
     * @return 令牌响应
     */
    @PostMapping("/code")
    public ResponseEntity<Map<String, Object>> getToken(@RequestParam String code) {
        log.info("收到授权码换取令牌请求: {}", code);
        try {
            Map<String, Object> tokenResponse = tokenService.getTokenByCode(code, "http://localhost:8080/callback");
            
            // 构建前端友好的响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("token_info", tokenResponse);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取令牌失败", e);
            
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", "获取令牌失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 使用刷新令牌获取新令牌
     * 
     * @param refreshToken 刷新令牌
     * @return 新令牌响应
     */
    @PostMapping("/refresh")
    public ResponseEntity<Map<String, Object>> refreshToken(@RequestParam String refreshToken) {
        log.info("收到刷新令牌请求");
        try {
            Map<String, Object> tokenResponse = tokenService.refreshToken(refreshToken);
            
            // 构建前端友好的响应
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("token_info", tokenResponse);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("刷新令牌失败", e);
            
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", "刷新令牌失败: " + e.getMessage());
            
            return ResponseEntity.badRequest().body(error);
        }
    }
}
